<?php
namespace AdminBundle\Model;

use RedUnicorn\SymfonyKernel\Appoint\Model\BuiltInDataInterface;
use RedUnicorn\SymfonyKernel\Model\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use RedUnicorn\Validate\Validate;
use AdminBundle\Entity\Admin;

class m_admin extends Model implements BuiltInDataInterface
{

    /**
     * @var Admin
     */
    private $admin_class = null;

    public function __construct(ContainerInterface $container = null)
    {
        parent::__construct($container, 'admin');
    }

    public function validate($data, $id = false)
    {
        $this->entityManager = $this->getDoctrine()->getManager();
        
        if(empty($id)){
            $this->admin_class = new Admin();
        }else{
            if(!$this->is_exist($id)){
                self::$error->setError($this->get('translator')->trans('未找到对应信息'));
                return false;
            }

            $this->admin_class = $this->entityManager->getRepository(Admin::class)->find($id);
        }

        if(array_key_exists('name', $data)){
            $this->admin_class->setName($data['name']);
        }

        if(array_key_exists('account', $data)){
            $is_exit = $this->is_exist(
                $data['account'],
                'account',
                [],
                $id
            );
            if (empty($id)) {
                if ($is_exit == true) {
                    self::$error->setError('账号已存在');
                }
            }
            $this->admin_class->setAccount($data['account']);
        }

        if(array_key_exists('password', $data)){
            if (!Validate::isPassword($data['password'])){
                self::$error->setError('密码格式不正确');
            }

            $this->admin_class->setSalt($this->get('unicorn.string')->generateSalt(4));
            $this->admin_class->setPassword($this->get('unicorn.string')->encryptPassword($data['password'], $this->admin_class->getSalt()));
        }

        if(array_key_exists('salt', $data)){
            $this->admin_class->setSalt($data['salt']);
        }
                
        if(array_key_exists('is_disable', $data)){
            $this->admin_class->setIsDisable($data['is_disable']);
        }
                
        if(array_key_exists('is_del', $data)){
            $this->admin_class->setIsDel($data['is_del']);
        }
                
        if(array_key_exists('is_built', $data)){
            $this->admin_class->setIsBuilt($data['is_built']);
        }
                
        if(array_key_exists('last_login_at', $data)){
            $this->admin_class->setLastLoginAt($data['last_login_at']);
        }
                
        if(array_key_exists('last_login_ip', $data)){
            $this->admin_class->setLastLoginIp($data['last_login_ip']);
        }
        
        if(self::$error->validate($this->admin_class)){
            return false;
        }
        
        return true;
    }
    
    public function insert($data)
    {
        if(!$this->validate($data)){
            return false;
        }
                                
        $this->admin_class->setCreateAt(new \DateTime()); 
   
        
        $this->entityManager->persist($this->admin_class);
        $this->entityManager->flush();
    
        $this->lastInsertId = $this->admin_class->getId();

        return true;
    }
    
    public function update($id ,$data)
    {
        if(empty($id)){
            self::$error->setError('id不能为空');
            return false;
        }
        
        if(!$this->validate($data, $id)){
            return false;
        }
                                
        $this->admin_class->setUpdateAt(new \DateTime()); 
   
        $this->entityManager->flush();

        return true;
    }
    
    public function rewritesRule(&$rule)
    {   
                    
        //where
        if(array_key_exists('id', $rule) && !empty($rule['id'])){
           $this->sql_array['where'] .= " AND sql_pre.id = '{$rule['id']}' ";
        }
                    
        // where   
        if(array_key_exists('name', $rule) && !Validate::isRealEmpty($rule['name'])){
            $this->sql_array['where'] .= " AND sql_pre.name LIKE '{$rule['name']}' ";
        }
                    
        // where   
        if(array_key_exists('account', $rule) && !Validate::isRealEmpty($rule['account'])){
            $this->sql_array['where'] .= " AND sql_pre.account LIKE '{$rule['account']}' ";
        }
                    
        // where   
        if(array_key_exists('password', $rule) && !Validate::isRealEmpty($rule['password'])){
            $this->sql_array['where'] .= " AND sql_pre.password LIKE '{$rule['password']}' ";
        }
                    
        // where   
        if(array_key_exists('salt', $rule) && !Validate::isRealEmpty($rule['salt'])){
            $this->sql_array['where'] .= " AND sql_pre.salt LIKE '{$rule['salt']}' ";
        }
                    
        // where   
        if(array_key_exists('is_disable', $rule)){
            $this->sql_array['where'] .= " AND sql_pre.is_disable = '{$rule['is_disable']}' ";
        }
                    
        // where   
        if(array_key_exists('is_del', $rule)){
            $this->sql_array['where'] .= " AND sql_pre.is_del = '{$rule['is_del']}' ";
        }else{
            $this->sql_array['where'] .= " AND sql_pre.is_del = 0 ";
        }
                    
        // where   
        if(array_key_exists('is_built', $rule)){
            $this->sql_array['where'] .= " AND sql_pre.is_built = '{$rule['is_built']}' ";
        }
                    
        // where   
        if(array_key_exists('create_at', $rule) && !Validate::isRealEmpty($rule['create_at'])){
            $this->sql_array['where'] .= " AND sql_pre.create_at LIKE '{$rule['create_at']}' ";
        }
                    
        // where   
        if(array_key_exists('update_at', $rule) && !Validate::isRealEmpty($rule['update_at'])){
            $this->sql_array['where'] .= " AND sql_pre.update_at LIKE '{$rule['update_at']}' ";
        }
                    
        // where   
        if(array_key_exists('last_login_at', $rule) && !Validate::isRealEmpty($rule['last_login_at'])){
            $this->sql_array['where'] .= " AND sql_pre.last_login_at LIKE '{$rule['last_login_at']}' ";
        }
                    
        // where   
        if(array_key_exists('last_login_ip', $rule) && !Validate::isRealEmpty($rule['last_login_ip'])){
            $this->sql_array['where'] .= " AND sql_pre.last_login_ip LIKE '{$rule['last_login_ip']}' ";
        }
            
    }
       
    /**
     * 重写删除方法 为delete()的嵌套重写方法
     *
     * @param $id
     * @return int
     * @throws \Doctrine\DBAL\DBALException
     */
    public function rewriteDelete($id)
    {
        return self::$conn->executeUpdate('UPDATE ' . $this->table_name . ' set is_del = 1 WHERE ' . $this->tel_sql_array['primary_key'] . ' in (' . $id . ')');
    }


    public function builtInData()
    {
        $salt = $this->get('unicorn.string')->generateSalt(4);
        $password = $this->get('unicorn.string')->encryptPassword('123456', $salt);

        self::$conn->insert('admin',array(
            'id' => $this->getParameter('super_id'),
            'name' => '超级管理员',
            'account' => 'aitime',
            'password' => $password,
            'salt' => $salt,
            'is_del' => 0,
            'create_at' => $this->get('unicorn.date')->curdatetime(),
            'is_built' => 1
        ));
    }
}